package com.dawn.framework.web.core.filter;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * @description:
 * @author: cnsu-cmh
 * @time: 2024/11/7 16:44
 */
@Slf4j
public class ChangeIpResponseFilter implements Filter {

    private String webPath;

    private String localPath;

    private String localIp;


    public ChangeIpResponseFilter() {
    }

    public ChangeIpResponseFilter(String webPath, String localPath, String localIp) {
        this.webPath = webPath;
        this.localPath = localPath;
        this.localIp = localIp;
    }


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        log.debug("httpRequest.getRequestURI() = [{}]",httpRequest.getRequestURI());
        // 检查请求的URL是否是你想要修改返回内容的特定请求
        // 外网
        if (httpRequest.getRequestURI().contains("app-api/cms")) {

        }
        if (httpRequest.getRequestURI().contains("admin-api/cms")
                || httpRequest.getRequestURI().contains("app-api/cms")
                || httpRequest.getRequestURI().contains("admin-api/hospital/medical-copy")
                || httpRequest.getRequestURI().contains("infra/file/upload")
                || httpRequest.getRequestURI().contains("infra/file/presigned-url")) {

            String serverName = httpRequest.getServerName();
            log.debug("serverName = [{}]",serverName);
            boolean intranet = serverName.equals(localIp);
            // 获取响应内容
            ChangerIpResponseWrapper responseWrapper = new ChangerIpResponseWrapper(httpResponse);
            chain.doFilter(httpRequest, responseWrapper);

            byte[] content = responseWrapper.getContent();
            String responseContent = new String(content, StandardCharsets.UTF_8);
            log.debug("responseContent = [{}]",responseContent);
            ServletOutputStream out = null;
            try {
                // 修改响应内容
                String modifiedContent = modifyContent(responseContent,intranet);

                // 设置修改后的响应内容
                response.setContentLength(modifiedContent.getBytes(StandardCharsets.UTF_8).length);
                out = response.getOutputStream();
                out.write(modifiedContent.getBytes(StandardCharsets.UTF_8));
            } catch (Exception e) {
                log.error("响应数据修改ip失败", e);
                throw new RuntimeException(e);
            } finally {
                if (out != null) {
                    out.flush();
                    out.close();
                }
            }

        } else {
            // 执行请求，此时响应内容还没有写入响应体
            chain.doFilter(request, response);
        }
    }

    private String modifyContent(String content, boolean intranet) {
        log.debug("intranet = [{}]",intranet);
        log.debug("modify before content = [{}]",content);
        if(StringUtils.isNotBlank(content)) {
            if(intranet) {
                content = content.replaceAll(webPath,localPath);
            } else {
                content = content.replaceAll(localPath,webPath);
            }
        }
        log.debug("modify after content = [{}]",content);
        return content;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // Filter初始化操作
    }

    @Override
    public void destroy() {
        // Filter销毁操作
    }
}
